<?php

namespace App\Http\Services\Admin;

use App\Http\Services\Service;
use App\Models\Admin\PermissionModel;
use Illuminate\Support\Facades\DB;

class PermissionService implements Service
{
    /**
     * 列表
     */
    public function index(array $params = []): array
    {
        return PermissionModel::all()->toArray();
    }

    /**
     * 分页列表
     */
    public function table(int $page, int $pageSize, array $params): array
    {
        $permissionModel = PermissionModel::query();
        $total = (clone $permissionModel)->count();
        $list = $permissionModel->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->orderBy('id', 'desc')
            ->get()
            ->toArray();
        return compact('total', 'list');
    }

    /**
     * 详情
     */
    public function find(int $id): array
    {
        return PermissionModel::query()->findOrFail($id)->toArray();
    }

    /**
     * 删除
     * @throws \Throwable
     */
    public function delete(array $ids): void
    {
        DB::beginTransaction();
        try {
            foreach ($ids as $id) {
                $permissionModel = PermissionModel::query()->findOrFail($id);
                $permissionModel->delete();
            }
            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            throw $e;
        }
    }

    public function checkAndReload(array $routes)  {
        $originSlugs = PermissionModel::query()->pluck('slug')->toArray();
        $newSlugs = array_keys($routes);

        $addSlugs = array_diff($newSlugs, $originSlugs);
        $delSlugs = array_diff($originSlugs, $newSlugs);

        if ($addSlugs) {
            PermissionModel::query()->insert(array_filter(
                $routes,
                fn($key) => in_array($key, $addSlugs),
                ARRAY_FILTER_USE_KEY
            ));
        }
        if ($delSlugs) {
            PermissionModel::query()->whereIn('slug', $delSlugs)->delete();
        }
    }
}
